package com.goxueche.lib_core.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.goxueche.lib_core.R;
import com.goxueche.lib_core.ui.mvp.presenter.IBasePresenter;
import com.goxueche.lib_core.widgets.title.AppTitle;
import com.goxueche.lib_core.widgets.title.TitleMgr;
import com.goxueche.lib_core.widgets.viewhelper.VaryViewHelper;

import java.util.Iterator;
import java.util.Map;

/**
 * @author 李澄锋<br>
 * 2018/8/13
 */
public abstract class BaseActivity<P extends IBasePresenter> extends FrameBaseActivity {
    private AppTitle appTitle;
    public VaryViewHelper mVaryViewHelper;
    private P mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        appTitle = new TitleMgr(getContext());
        appTitle.initTitle();
        View contentView = findViewById(R.id.core_content_layout);
        if (contentView != null) {
            initVaryView();
        }
        findViewById();
        initLayoutView();
    }

    protected void initVaryView() {
        if (loadingview() <= 0 || emptyview() <= 0 || errorview() <= 0) {
            return;
        }
        mVaryViewHelper = new VaryViewHelper.Builder()
                .setDataView(findViewById(R.id.core_content_layout))//放数据的父布局，逻辑处理在该Activity中处理
                .setLoadingView(LayoutInflater.from(this).inflate(loadingview(), null))//加载页，无实际逻辑处理
                .setEmptyView(LayoutInflater.from(this).inflate(emptyview(), null))//空页面，无实际逻辑处理
                .setErrorView(LayoutInflater.from(this).inflate(errorview(), null))//错误页面
                .setRefreshListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reloadData();
                    }
                })//错误页点击刷新实现
                .build();
    }

    public abstract void findViewById();

    /**
     * 初始化布局
     */
    public abstract void initLayoutView();

    public abstract int loadingview();

    public abstract int emptyview();

    public abstract int errorview();

    public void reloadData() {
        if (mVaryViewHelper != null) {
            mVaryViewHelper.showLoadingView();
        }
    }

    public AppTitle getAppTitle() {
        return appTitle;
    }

    public void setAppTitle(AppTitle appTitle) {
        this.appTitle = appTitle;
    }

    /**
     * 显示加载对话框
     */
    @Override
    public Dialog showWaitDialog(final boolean cancelable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null == dialog || !dialog.isShowing() ||
                        isFinishing() ||
                        isDestroyed()) {
                    dialog = new Dialog(getContext(), R.style.dialog_transparent);
                    View waitingView = getLayoutInflater().inflate(
                            R.layout.circular_progress, null);
                    waitingView.invalidate();
                    dialog.setContentView(waitingView);
                }
                try {
                    dialog.setCancelable(cancelable);
                    dialog.show();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        });
        return dialog;
    }

    /**
     * 创建 Presenter
     *
     * @return presenter
     */
    public abstract P onBindPresenter();

    /**
     * 获取 Presenter 对象，在需要获取时才创建`Presenter`，起到懒加载作用
     */
    public P getPresenter() {
        if (mPresenter == null) {
            mPresenter = onBindPresenter();
        }
        return mPresenter;
    }


    public interface onPermissionDialogCancelListener {
        void onCancel();

        void onOk();
    }

    public Intent getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", this.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", this.getPackageName());
        }
        return localIntent;
    }

    public void startActivity(Class<?> classActivity) {
        Intent intent = new Intent();
        intent.setClass(getContext(), classActivity);
        startActivity(intent);
    }

    public void startService(Class<?> toServiceClass) {
        Intent intent = new Intent();
        intent.setClass(getContext(), toServiceClass);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }

    public void startService(Class<?> toServiceClass, String action, Map<String, String> paramsMap) {
        Intent intent = new Intent();
        intent.setClass(getContext(), toServiceClass);
        if (!TextUtils.isEmpty(action)) {
            intent.setAction(action);
        }
        if (paramsMap != null && paramsMap.size() > 0) {
            Iterator<Map.Entry<String, String>> entries = paramsMap.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, String> entry = entries.next();
                if (!TextUtils.isEmpty(entry.getKey()) && !TextUtils.isEmpty(entry.getValue())) {
                    intent.putExtra(entry.getKey(), entry.getValue());
                }
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }

    @Override
    protected void onDestroy() {
        if (mVaryViewHelper != null) {
            mVaryViewHelper = null;
        }
        super.onDestroy();
    }
}
